<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Models\User;
use App\Http\Models\UserAppKey;
use Carbon\Carbon;
use Auth;
use DB;
use Validator;
/*
* 用户开放API，获取KEY
*/
class UserAppKeyController extends Controller
{
    
	//获取用户APPKEY
    public function getAppKey()
    {
		$uid = Auth::id();//获取当前登陆用户ID
		if (empty($uid)) {
			return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
		}
		$key = UserAppKey::where('user_id', $uid)->first();
		if(empty($key)){
			return response()->json(['code' => 1, 'msg' => '不存在appkey']);
		}
        return response()->json(['code' => 0, 'msg' => 'ok', 'data' => ['appkey'=>$key->appkey]]);
    }
	//检测appkey
	public function checkAppKey(Request $request)
	{
		$phone = request('phone');//获取用户ID
		$key = request('appkey');//获取用户key
		if (empty($phone) || empty($key)) {
			return json_encode(['code' => 1, 'msg' => '参数不全，需要phone和appkey！']);
		}
		$user = UserAppKey::where(['phone'=>$phone,'appkey'=>$key])->first();
		if(empty($user)){
			return response()->json(['code' => 1, 'msg' => 'appkey无效']);
		}
		return response()->json(['code' => 0, 'msg' => 'appkey有效']);
	}
	//重置appkey接口
	public function resetAppKey()
	{
		$uid = Auth::id();//获取当前登陆用户ID
		if (empty($uid)) {
			return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
		}
		$user=User::where('id',$uid)->first();
		$appkey=getMDappkey($user->phone);//获取生成的appkey
		
		//判断是否已经有key
		$key = UserAppKey::where('user_id', $uid)->first();
		$sid=null;
		if(empty($key)){
			//如果不存在key,则新添加key
			$sid = UserAppKey::insert([
				'user_id' => $uid,
				'appkey' => $appkey,
				'created_at' => date('y-m-d h:i:s', time()),
				'phone' => $user->phone
			]);
		}else{
			//如果存在,则更新key
			$sid = UserAppKey::where('user_id', $uid)->update([
					'appkey' => $appkey,
					'updated_at' => date('y-m-d h:i:s', time()),
					'phone' => $user->phone
				]);
		}
		if(!$sid){
			return response()->json(['code' => 1, 'msg' => '重置appkey失败']);
		}		
		return response()->json(['code' => 0, 'msg' => 'ok', 'data' => ['appkey'=>$appkey]]);	
	}
	
}
